package com.exrobot.module.rbt.framework.mqtt;

import com.exrobot.module.rbt.enums.MqttTopicSubEnum;
import com.exrobot.module.rbt.service.mqtt.MqttMessageService;
import com.exrobot.module.rbt.service.robotoperationlog.RobotOperationLogService;
import com.xkcoding.http.util.StringUtil;
import jakarta.annotation.Resource;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

@Configuration
@EnableIntegration // 启用 Spring Integration
@IntegrationComponentScan // 扫描 @MessagingGateway 等组件
public class MqttConfig {

    @Value("${spring.mqtt.username}")
    private String username;

    @Value("${spring.mqtt.password}")
    private String password;

    @Value("${spring.mqtt.url}")
    private String hostUrl;

    @Value("${spring.mqtt.client-id}")
    private String clientId;

    @Value("${spring.mqtt.default-topic}")
    private String defaultTopic;

    @Resource
    private MqttMessageService mqttMessageService;
    /**
     * 创建MQTT客户端工厂//    @Lazy
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setServerURIs(new String[]{hostUrl});
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，
        // 这里设置为true表示每次连接到服务器都以新的身份连接
        options.setCleanSession(false);
        // 设置自动重连
        options.setAutomaticReconnect(true);
        // 设置连接超时
        options.setConnectionTimeout(10);
        // 设置会话保持时间
        options.setKeepAliveInterval(60);
        factory.setConnectionOptions(options);
        return factory;
    }

    /**
     * 发送消息的通道
     */
    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /**
     * 配置MQTT消息发送处理器
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
                clientId + "_sender", mqttClientFactory());
        messageHandler.setAsync(true); // 异步发送
        messageHandler.setDefaultTopic(defaultTopic);
        messageHandler.setConverter(new DefaultPahoMessageConverter());
        return messageHandler;
    }

    /**
     * 接收消息的通道
     */
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    /**
     * 配置MQTT消息接收适配器
     */
    @Bean
    public MqttPahoMessageDrivenChannelAdapter inbound() {
        String topicArr[] = MqttTopicSubEnum.ARRAYS;
        int qosArr[] = new int[topicArr.length];
        for (int i = 0; i < topicArr.length; i++) {
            qosArr[i] = 1;
            topicArr[i] = defaultTopic + topicArr[i];
        }
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(clientId + "_receiver", mqttClientFactory(), topicArr);
        adapter.setCompletionTimeout(5000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(qosArr); // 设置消息质量
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    /**
     * 消息接收处理器
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return message -> {
            String payload = message.getPayload().toString();
            String topic = message.getHeaders().get("mqtt_receivedTopic").toString().replace(defaultTopic,"");
            // 在这里处理接收到的消息
            if(StringUtil.isEmpty(payload)){
                return;
            }
            mqttMessageService.messageHanding(topic, payload);
        };
    }
}
